//
//  MyContactDemandTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/3.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "MyContactDemandTabVC.h"
#import "MyContactDemandCell.h"
#import "RelationModel.h"
#import "HomeModel.h"
#import "ServiceModel.h"
@interface MyContactDemandTabVC ()<MyContactDemandCellDelegate>
@property(nonatomic,strong) NSMutableArray *demandArray;
@property(nonatomic,strong) NSMutableArray *relationArray;
@property(nonatomic,assign) NSInteger uid;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,assign) NSInteger pageNumber;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSString *ids;
@property(nonatomic,strong) RelationModel *relationModel;
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,assign) NSInteger relationStatus;
@end
static NSString *identifierDemand = @"Cell";
@implementation MyContactDemandTabVC
-(NSMutableArray *)relationArray
{
    if (!_relationArray) {
        _relationArray = [NSMutableArray array];
    }
    return _relationArray;
}
-(NSMutableArray *)demandArray
{
    if (!_demandArray) {
        _demandArray = [NSMutableArray array];
    }
    return _demandArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [AFHTTPSessionManager manager];
    self.relationModel =[[RelationModel alloc]init];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:@"MyContactDemandCell" bundle:nil] forCellReuseIdentifier:identifierDemand];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateRelation:) name:@"updateRelation" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relationselectRelation:) name:@"relationselectRelation" object:nil];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_header = header;
    [header beginRefreshing];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
    self.tableView.mj_footer = footer;
                [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                footer.stateLabel.font = [UIFont systemFontOfSize:12];
                footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    
}
-(void)refresh
{
    self.relationArray = nil;
    self.demandArray = nil;
    self.pageSize = 10;
    self.pageNumber = 1;
    self.uid = 1;
    [self reloadInternetRelation];
}
-(void)reloadMore
{
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    self.pageNumber ++;
    [self reloadInternetRelation];
    
}
#pragma mark-查询relation
-(void)reloadInternetRelation
{
//    NSString *uids = [NSString stringWithFormat:@"%ld",self.uid];
    NSString *pageNums = [NSString stringWithFormat:@"%ld",self.pageNumber];
    NSString *pageSizes = [NSString stringWithFormat:@"%ld",self.pageSize];
    self.urlString = [NSString stringWithFormat:@"%@/relation/selectRelation",kUrl];
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"pageSize":pageSizes,
                  @"pageNumber":pageNums,
                  @"token":[UserDefaultsHelper readToken]
                  };
    XLog(@"self.dict:%@",self.dict);
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"MyContactDemandTabVC:%@",responseObject);
        NSArray *date = [responseObject objectForKey:@"date"];
        if (date.count) {
            for (NSDictionary *dict in date) {
                HomeModel *homeModel = [HomeModel mj_objectWithKeyValues:dict];
                [self.demandArray addObject:homeModel];
                RelationModel *model = [RelationModel mj_objectWithKeyValues:dict];
                [self.relationArray addObject:model];
            }
            [self.tableView reloadData];
            [WSProgressHUD dismiss];
            if (date.count< 10) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
        }else {
            [WSProgressHUD dismiss];
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"error:%@",error);
    }];


}
//#pragma mark-获取内容
//-(void)reloadInternetDate
//{
//    XLog(@"self.relationArray:%@",self.relationArray);
//    //使用GCD的信号量 dispatch_semaphore_t 创建同步请求
//    dispatch_group_t group =dispatch_group_create();
//    dispatch_queue_t globalQueue=dispatch_get_global_queue(0, 0);
//    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
//    dispatch_group_async(group, globalQueue, ^{
//        for (int i = 0; i<self.relationArray.count; i++) {
//            RelationModel *model = self.relationArray[i];
//            NSString *ids = [NSString stringWithFormat:@"%ld",model.id];
//            self.urlString = [NSString stringWithFormat:@"%@/demand/selectDemandByIds",kUrl];
//            self.dict = @{
//                          @"ids":ids
//                          };
//            XLog(@"self.dict:%@",self.dict);
//            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                XLog(@"HomeresponseObject:%@",responseObject);
//                NSArray *temp =[responseObject objectForKey:@"date"];
//                XLog(@"temp:%@",temp);
////                XLog(@"temp.count:%ld",temp.count);
//                NSInteger empty = [EmptyModel stringIsNullOrEmpty:temp];
//                  if (empty !=1) {
//                      for (NSDictionary *dict in temp) {
//                          HomeModel *model = [HomeModel mj_objectWithKeyValues:dict];
//                          [self.demandArray addObject:model];
//                      }
//                  }else {
//                      [WSProgressHUD dismiss];
//                      self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
//                  }
//
//                dispatch_semaphore_signal(semaphore);
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                XLog(@"error:%@",error);
//                dispatch_semaphore_signal(semaphore);
//            }];
//            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//        }
//
//    });
//
//    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
//        XLog(@"%@---全部结束。。。",[NSThread currentThread]);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableView reloadData];
//            [WSProgressHUD dismiss];
//            [self.tableView.mj_header endRefreshing];
//            [self.tableView.mj_footer endRefreshing];
//        });
//    });
//}

//-(void)reloadInternetDate
//{
//
//}
//-(void)dealloc
//{
//    [[NSNotificationCenter defaultCenter]removeObserver:self];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.relationArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    MyContactDemandCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierDemand forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.indexPath = indexPath;
//    HomeModel *model = self.demandArray[indexPath.row];
//    cell.model = model;
//    XLog(@"self.demandArray:%@",self.demandArray);
//    XLog(@"model:%@",model.represent);
    RelationModel *relationModel = self.relationArray[indexPath.row];
    cell.relationModel = relationModel;
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     HomeModel *homeModel = self.demandArray[indexPath.row];
    if (self.returnValueBlock) {
        self.returnValueBlock(homeModel);
    };
}
#pragma mark-代理:显示联系人
-(void)myContactDemandCell:(MyContactDemandCell *)myContactDemandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(nonnull NSIndexPath *)indexPath withHomeModel:(nonnull RelationModel *)relationModel
{
//    HomeModel *model = self.demandArray[indexPath.row];
    relationModel.show = clickBtn.selected;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    
}
#pragma mark-代理:真假评价
-(void)myContactDemandCell:(MyContactDemandCell *)myContactDemandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath
{
    self.relationModel = self.relationArray[indexPath.row];
//    if (clickBtn.tag == 0) {//评价:假
    self.relationStatus = clickBtn.tag;
//    }else {
//
//    }
    self.indexPath = indexPath;
    [self reloadRelationDate];
}
-(void)reloadRelationDate
{
    
    NSString *ids = self.relationModel.id;
    NSString *status = [NSString stringWithFormat:@"%ld",self.relationStatus];
    self.dict = @{
                  @"id":ids,
                  @"status":status,
                  @"token":[UserDefaultsHelper readToken],
                  @"uid":[UserDefaultsHelper readUid]
                  };
    XLog(@"%@",self.dict);
    [CustomeManager POSTWithURLIndex:39 parameters:self.dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark-代理:更新评价
-(void)updateRelation:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSString *message = [info.userInfo objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD dismiss];
        XLog(@"%ld---%ld",self.indexPath.section,self.indexPath.row);
        RelationModel *relationModel = self.relationArray[self.indexPath.row];
        relationModel.relationStatus = self.relationStatus;
//        relationModel.status  = [NSString stringWithFormat:@"%ld",self.statu];
        [self.tableView reloadRowsAtIndexPaths:@[self.indexPath] withRowAnimation:UITableViewRowAnimationNone];
    });
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 144;
}
@end
